package com.spi.config;

import com.spi.init.ServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private RedisTemplate redisTemplate ;
    @Autowired
    private ServerInfo serverInfo ;

    //存储所有连接的websocket会话
    public static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //当websocket建立连接时 将会话添加到sessions中
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("websocket建立连接。。。");
//        String path = session.getUri().getPath();
//        String query = session.getUri().getQuery(); //id=1
//        redisTemplate.opsForSet().add("cloud-websocket",query);
        //redisTemplate.opsForValue().set(query,new Date().getTime());
        String sockId = UUID.randomUUID().toString();
        System.out.println("生成socketid为" +  sockId);
        log.info("生成socketid为" +  sockId);
        sessions.put(sockId, session);
        redisTemplate.opsForValue().set(sockId,serverInfo.getAddress(),30, TimeUnit.MINUTES);
        session.sendMessage(new TextMessage("sockId:" + sockId));
    }

    //处理前端发送的信息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        String payload = message.getPayload();
//        if ("getSessionId".equals(payload)) {
////            boolean exists = redisTemplate.opsForSet().isMember("cloud-websocket",session.getUri().getQuery());
////            String reValue = (String)redisTemplate.opsForValue().get(session.getUri().getQuery());
////            String sessionId = UUID.randomUUID().toString();
////            String sessionId = session.getId();
//            String sessionId = session.getId();
//            session.sendMessage(new TextMessage("sessionId:" + sessionId));
////            if (exists){
////                session.sendMessage(new TextMessage("sessionId:" + session.getUri().getQuery()));
////                System.out.println("websocket获取redis中value" + session.getUri().getQuery());
////            }
//
//        }
        System.out.println("进入到handleTextMessage。。。");
        log.info("进入到afterConnectionClosed。。。");
    }

    //当websocket连接关闭时，移除该会话
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        sessions.remove(session.getId());
        //redisTemplate.delete(session.getUri().getQuery());
    }

    //遍历所有会话 向所有打开的会话发送消息
    public static void sendMessageToClient(String sessionId, String message) {
        if (!sessions.containsKey(sessionId)) {
            System.out.println("当前服务无该websocket连接信息。。。直接退出");
            log.info("当前服务无该websocket连接信息。。。直接退出");

            return;
        }
        System.out.println("websocket遍历会话。。。");
        log.info("websocket遍历会话。。。");
//        if (!redisTemplate.hasKey(s.getUri().getQuery())){
//                continue;
//            }

        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            WebSocketSession s = entry.getValue();
//            if (!redisTemplate.hasKey(s.getUri().getQuery())){
//                continue;
//            if (!s.getUri().getQuery().equals(sessionId)) {
//                //判断请求携带的sessionid与本次循环的sessionid是否一致 不一致循环下一个id
//                continue;
//            }
            if (!entry.getKey().equals(sessionId)) {
                //判断请求携带的sessionid与本次循环的sessionid是否一致 不一致循环下一个id
                continue;
            }
            //只当当前页面没有进行关闭时才会进行通知。。
            if (s.isOpen()) {
                try {
                    s.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
